<template>
    <div id="app">
        <div class="swiper-container" id="banner">
            <div class="swiper-wrapper">
                <div class="swiper-slide">
                    <router-link to="/detail"><img src="@/assets/travel/images/banner01.jpg" alt=""></router-link>
                </div>
                <div class="swiper-slide">
                    <router-link to="/detail"><img src="@/assets/travel/images/banner02.jpg" alt=""></router-link>
                </div>
                <div class="swiper-slide">
                    <router-link to="/detail"><img src="@/assets/travel/images/banner03.jpg" alt=""></router-link>
                </div>
            </div>

            <div class="swiper-pagination"></div>
        </div>

        <div class="cate">
            <router-link to="/travel/eat"><img src="@/assets/travel/images/icon01.png" alt="">吃在滨海</router-link>
            <router-link to="/travel/play"><img src="@/assets/travel/images/icon02.png" alt="">玩在滨海</router-link>
            <router-link to="/travel/live"><img src="@/assets/travel/images/icon03.png" alt="">住在滨海</router-link>
            <router-link to="/travel/buy"><img src="@/assets/travel/images/icon04.png" alt="">购在滨海</router-link>
        </div>

        <h1 class="bt">
            <router-link to="/travel/eat">吃在滨海<img src="@/assets/travel/images/more.png" alt=""></router-link>
        </h1>
        <ul class="list">
            <image-table-list :list="list.eatList"></image-table-list>
        </ul>

        <h1 class="bt">
            <router-link to="/travel/play">玩在滨海<img src="@/assets/travel/images/more.png" alt="">
            </router-link>
        </h1>
        <ul class="list">
            <image-table-list :list="list.playList"></image-table-list>
        </ul>

        <h1 class="bt">
            <router-link to="/travel/live">住在滨海<img src="@/assets/travel/images/more.png" alt=""></router-link>
        </h1>
        <ul class="list">
            <image-table-list :list="list.liveList"></image-table-list>
        </ul>

        <h1 class="bt">
            <router-link to="/travel/buy">购在滨海<img src="@/assets/travel/images/more.png" alt=""></router-link>
        </h1>
        <ul class="list">
            <image-table-list :list="list.travelList"></image-table-list>
        </ul>
    </div>
</template>

<script>
    import Vue from 'vue'
    import axios from 'axios'
    import Swiper from 'swiper';
    import 'swiper/dist/css/swiper.min.css';
    import imageTableList from '@/componets/image-table';
    import home from '@/api/travel/home';

    // 获取用户信息
    // code:部门 100：卫健委；101：体育局；102：供水公司；103：住建局；104：文广旅居
    async function getInfo(appId, keyId, userDataTypes) {
        const baseUrl = Vue.prototype.baseUrl; // 服务器地址
        // 初始化api sdk
        await fetchInitCode(appId, keyId, userDataTypes, baseUrl)
    }

    // 初始化api sdk
    async function fetchInitCode(appId, keyId, userDataTypes, baseUrl) {
        const time = sessionStorage.getItem('initCodeTime');
        if (time) {
            // 有code时直接运行
            const lastTime = new Date().getTime() - time;
            if (lastTime < 300000) {
                console.log("initCodeTime生效中，无需获取新的initCode");
                await forAuthPop(appId, keyId, userDataTypes, baseUrl);
                return
            }
        }
        await axios
            .get(`${baseUrl}/getInitCode/${keyId}`, {timeout: 20000})
            .then((res) => {
                const {initCode} = res.data.data;
                sessionStorage.setItem('initCodeTime', new Date().getTime());

                if (!initCode) return;

                // 初始化api sdk
                sc.config({
                    debug: false, // 是否开启调试模式,调用的所有 api 的返回值会在客户端 alert 出来
                    appId: appId, // 在统一 APP 开放平台服务器申请的 appId
                    initCode: initCode
                });

                //注册成功之后执行
                sc.ready(() => {
                    console.log("初始化完成，校验是否弹出授权");
                    // 校验是否需要弹起授权
                    forAuthPop(appId, keyId, userDataTypes, baseUrl)
                });

                sc.error(() => {
                    sc.toast({
                        text: '网络正在开小差~~',
                    });
                    sessionStorage.setItem('initCodeTime', '')
                })
            })
            .catch(function () {
                sc.toast({
                    text: '网络正在开小差~~',
                });
                setTimeout(() => {
                    sc.goback();
                    if (window.loadingInfo) {
                        window.loadingInfo.close()
                    }
                }, 1500)
            })
    }

    // 弹起授权
    async function forAuthPop(appId, keyId, userDataTypes, baseUrl) {
        const time = sessionStorage.getItem(`userAccessTokenTime${keyId}`);
        if (time) {
            if (new Date().getTime() - time < 2 * 60 * 60 * 1000) {
                console.log("userAccessTokenTime生效中  无需授权");
                const userAccessToken = JSON.parse(sessionStorage.getItem(`userAccessToken${code}`));
                await fetchUserInfo(appId, keyId, userDataTypes, baseUrl, userAccessToken);
                return
            }
        }

        // 获取授权
        sc.userAuth({
            appId: appId,
            userDataTypes: userDataTypes
        }, (ress) => {
            if (ress.code === 0) {
                // 根据得到的requestCode 进行校验
                axios.post(`${baseUrl}/checkRequestCode`, {
                    requestCode: ress.data.requestCode,
                    keyId: keyId,
                    appId: appId
                })
                    .then((response) => {
                        // 授权成功
                        sessionStorage.setItem(`userAccessToken${keyId}`, JSON.stringify(response.data.data.userAccessToken));
                        sessionStorage.setItem(`userAccessTokenTime${keyId}`, new Date().getTime());
                        // fetchUserInfo(appId, keyId, userDataTypes, baseUrl, response.data.data.userAccessToken, that, fun)
                    })
            } else {
                setTimeout(() => {
                    sc.goback();
                    if (window.loadingInfo) {
                        window.loadingInfo.close()
                    }
                }, 1500);
                if (ress.code === -10001) {
                    sc.toast({
                        text: '初始化失败',
                    });
                } else if (ress.code === -10002) {
                    sc.toast({
                        text: '您已拒绝授权~~',
                    });
                } else if (ress.code === -10003) {
                    sc.toast({
                        text: '您还未登录~~',
                    });
                } else {
                    sc.toast({
                        text: '网络正在开小差~~',
                    });
                }
            }
        })

    }

    // 获取用户信息
    async function fetchUserInfo(appId, keyId, userDataTypes, baseUrl, userAccessToken, that, fun) {
        await axios.post(`${baseUrl}/getUserInfo`, {
            userAccessToken: userAccessToken
        })
            .then((res) => {
                if (res.data.code !== 200) {
                    sc.toast({
                        text: '获取用户信息失败~~',
                    });
                    setTimeout(() => {
                        sc.goback();
                        if (window.loadingInfo) {
                            window.loadingInfo.close()
                        }
                    }, 1500)
                } else if (res.data.data.realNameStatus) {
                    console.log("已实名");
                    // 用户实名则结束
                    sessionStorage.setItem('userInfo', JSON.stringify(res.data.data));
                    // const self = that;
                    // fun();
                    // self.isRouterAlive = true;
                    // if (window.loadingInfo) {
                    //     window.loadingInfo.close();
                    //     window.loadingInfo = null
                    // }
                } else {
                    console.log("未实名");
                    //  未实名需要先实名
                    // isRealName(appId, keyId, userDataTypes, baseUrl, that, fun)
                }
            })
    }

    // 是否实名认证
    async function isRealName(appId, keyId, userDataTypes, baseUrl, that, fun) {
        if (window.loadingInfo) {
            window.loadingInfo.close()
        }
        window.dia = Dialog({
            // 成功，当传入infoType为0时，可得到认证人脸图片
            message: '开始实名认证',
            buttons: [
                {
                    active: true,
                    text: '取消',
                    handler(hide) {
                        hide();
                        sc.goback()
                    }
                },
                {
                    active: true,
                    text: '确定',
                    handler(hide) {
                        hide();
                        sc.verify(
                            {
                                infoType: '0'
                            },
                            (res1) => {
                                if (res1.code === 0) {
                                    // 再次获取用户信息
                                    fetchUserInfo(appId, keyId, userDataTypes, baseUrl, JSON.parse(localStorage.getItem(`userAccessToken${keyId}`), that, fun))
                                } else {
                                    sc.toast({
                                        text: '实名失败~~',
                                    });
                                    setTimeout(() => {
                                        sc.goback();
                                        if (window.loadingInfo) {
                                            window.loadingInfo.close()
                                        }
                                    }, 1500)
                                }
                            }
                        )
                    }
                }
            ]
        })
    }

    export default {
        data() {
            return {
                list: {
                    eatList: [],
                    playList: [],
                    liveList: [],
                    travelList: []
                },
            }
        },
        components: {
            imageTableList
        },
        methods: {
            getEatList() {
                home.getListByType(1, 4, '00').then(response => {
                    this.list.eatList = response.data.data;
                });
            },
            getPlayList() {
                home.getListByType(1, 4, '01').then(response => {
                    this.list.playList = response.data.data;
                });
            },
            getLiveList() {
                home.getListByType(1, 4, '02').then(response => {
                    this.list.liveList = response.data.data;
                });
            },
            getTravelList() {
                home.getListByType(1, 4, '03').then(response => {
                    this.list.travelList = response.data.data;
                });
            }
        },
        created() {
            getInfo("deaac0d8e335478fa1f77d14dc708158", "104"); //文旅局
            this.getEatList();
            this.getPlayList();
            this.getLiveList();
            this.getTravelList();
        },
        mounted() {
            new Swiper('#banner', {
                loop: true,
                speed: 1000,
                centeredSlides: true,
                autoplay: 3000,
                pagination: '.swiper-pagination',
            })
        }
    }
</script>

<style scoped></style>
